<?php
namespace Admin\Model;
use  Think\Model;
class BannerModel extends Model{
	//添加轮播图
	public function addDo(){
		if(!empty($_FILES['pic']['name'])){
			$info=$this->upFile();
			if($info['msg']==0){
				echo $info['info'];
			}
			if($info['msg']==1){
			$data['pic']=$info['info']['pic']['savepath'].$info['info']['pic']['savename'];
			}
		}else{
			unset($_POST['pic']);
		}
		$data['name']=I('post.name');
		$data['url']=I('post.url');
		$data['sort']=I('post.sort');
		M('banner')->add($data);
		return true;
	}

	//跟新轮播图
	public function editDo(){
		if(!empty($_FILES['pic']['name'])){
			//说明要跟新图片
			//所以要删除原来的图片文件
			$pic=M('banner')->where(array('id'=>I('id','','intval')))->field('id,pic')->find();
			$url='./'.$pic['pic'];
			if(file_exists($url)){
				unlink($url);
			}
			$info=$this->upFile();
			if($info['msg']==0){
				echo $info['info'];
			}
			if($info['msg']==1){
			$data['pic']=$info['info']['pic']['savepath'].$info['info']['pic']['savename'];
			}
		}else{
			$data['pic']=I('post.pic');
		}
		    $data['name']=I('post.name');
		    $data['sort']=I('post.sort');
		    $data['url']=I('post.url');
		    $id=I('post.id');
            M('banner')->where('id='.$id)->save($data);
            return true;
	}

	//删除轮播图
	public function del(){
		$id=I('id','','intval');
		$pic=M('banner')->where('id='.$id)->field('pic')->find();
		$url='./'.$pic['pic'];
		if(file_exists($url)){
			unlink($url);
		}
		$info=M('banner')->where('id='.$id)->delete();
		return $info;
	}
	//上传图片的方法
	public function upFile(){
		$upload=new \Think\Upload();      //实例化上传类
		$upload->maxSize =3*1024*1024;     //上传的最大的大小
		$upload->exts =array('jpg','gif','png','jpeg'); //允许上传的格式
		$upload->rootPath='./';            //文件上传保存的根目录
		$upload->savePath='Uploads/Banner/';  //上传文件的子目录
		$upload->authSub=false;             //不自动使用子目录
		$upload->savename='uniqid';    

		$info=$upload->Upload();    //上传
		if(!$info){
			$pic=array(
				'msg'  =>0,
				'info' =>$upload->getError()
                );
		}else{
			$pic=array(
				'msg'  =>1,
				'info' =>$info
				);
            
		}
		return $pic;    

	}
}